import React, { useState, useRef, useEffect } from 'react';
import Head from 'next/head';
import { 
  Layout, Typography, Upload, Button, Input, 
  message, Spin, Card, Row, Col, Select, Divider,
  InputNumber, Space, Tooltip
} from 'antd';
import { 
  InboxOutlined, SwapOutlined, UploadOutlined,
  FontColorsOutlined, FontSizeOutlined, DeleteOutlined
} from '@ant-design/icons';
import { SketchPicker } from 'react-color';
import { imageApi } from '../../services/api';

const { Header, Content, Footer } = Layout;
const { Title, Text, Paragraph } = Typography;
const { Dragger } = Upload;
const { Option } = Select;

const TextReplaceTool = () => {
  // 状态管理
  const [file, setFile] = useState(null);
  const [imageUrl, setImageUrl] = useState('');
  const [fileId, setFileId] = useState('');
  const [uploading, setUploading] = useState(false);
  const [processing, setProcessing] = useState(false);
  const [resultImageUrl, setResultImageUrl] = useState('');
  
  // 文字替换相关状态
  const [originalText, setOriginalText] = useState('');
  const [newText, setNewText] = useState('');
  const [fontFamily, setFontFamily] = useState('Arial');
  const [fontSize, setFontSize] = useState(24);
  const [fontColor, setFontColor] = useState('#000000');
  const [showColorPicker, setShowColorPicker] = useState(false);
  
  // 字体列表
  const fontOptions = [
    { label: 'Arial', value: 'Arial' },
    { label: 'Helvetica', value: 'Helvetica' },
    { label: 'Times New Roman', value: 'Times New Roman' },
    { label: 'Courier New', value: 'Courier New' },
    { label: 'Georgia', value: 'Georgia' },
    { label: 'Verdana', value: 'Verdana' }
  ];
  
  // 重置状态
  const resetStates = () => {
    setFile(null);
    setImageUrl('');
    setFileId('');
    setResultImageUrl('');
    setOriginalText('');
    setNewText('');
    setFontFamily('Arial');
    setFontSize(24);
    setFontColor('#000000');
  };
  
  // 处理文件上传
  const handleFileUpload = async (file) => {
    try {
      setUploading(true);
      
      // 验证文件类型
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        message.error('只能上传图片文件!');
        return false;
      }
      
      // 验证文件大小
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        message.error('图片大小不能超过5MB!');
        return false;
      }
      
      // 读取图片本地预览
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        setImageUrl(reader.result);
      };
      
      // 上传图片到服务器
      const formData = new FormData();
      formData.append('file', file);
      
      const response = await imageApi.uploadImage(file);
      
      if (response.data && response.data.fileId) {
        setFileId(response.data.fileId);
        message.success('图片上传成功');
      } else {
        message.error('图片上传失败');
      }
      
      setFile(file);
      return false; // 阻止默认上传行为
    } catch (error) {
      console.error('上传图片失败:', error);
      message.error('上传图片失败: ' + error.message);
    } finally {
      setUploading(false);
    }
  };
  
  // 执行文字替换
  const handleTextReplace = async () => {
    if (!fileId) {
      message.error('请先上传图片');
      return;
    }
    
    if (!originalText) {
      message.error('请输入需要替换的原始文字');
      return;
    }
    
    if (!newText) {
      message.error('请输入替换后的文字');
      return;
    }
    
    try {
      setProcessing(true);
      
      // 准备请求数据
      const textReplaceData = {
        originalText,
        newText,
        fontFamily,
        fontSize,
        fontColor
      };
      
      // 调用API
      const response = await imageApi.textReplaceImage(fileId, textReplaceData);
      
      if (response.data && response.data.downloadUrl) {
        setResultImageUrl(response.data.downloadUrl);
        message.success('文字替换成功');
      } else {
        message.error('文字替换失败');
      }
    } catch (error) {
      console.error('文字替换失败:', error);
      message.error('文字替换失败: ' + error.message);
    } finally {
      setProcessing(false);
    }
  };
  
  // 上传组件配置
  const uploadProps = {
    name: 'file',
    multiple: false,
    showUploadList: false,
    beforeUpload: handleFileUpload,
    accept: 'image/*'
  };
  
  return (
    <Layout className="layout">
      <Head>
        <title>图像文字替换 - 在线工具</title>
        <meta name="description" content="替换图片中的文字内容，在线快速编辑图片文字" />
      </Head>
      
      <Header className="header">
        <div className="logo" />
        <Title level={4} style={{ color: 'white', margin: '0' }}>在线工具平台</Title>
      </Header>
      
      <Content style={{ padding: '0 50px' }}>
        <div className="site-layout-content" style={{ padding: 24, minHeight: 'calc(100vh - 64px - 70px)' }}>
          <Title level={2}>图像文字替换</Title>
          <Paragraph>上传图片，替换图片中的文字内容</Paragraph>
          
          <Divider />
          
          <Row gutter={[16, 16]}>
            <Col xs={24} sm={24} md={12} lg={12}>
              <Card title="上传图片" bordered={false}>
                <Dragger {...uploadProps} style={{ marginBottom: 16 }}>
                  <p className="ant-upload-drag-icon">
                    <InboxOutlined />
                  </p>
                  <p className="ant-upload-text">点击或拖拽图片到此处上传</p>
                  <p className="ant-upload-hint">
                    支持单个图片上传，格式包括JPG、PNG、GIF等，大小不超过5MB
                  </p>
                </Dragger>
                
                {uploading && <Spin tip="上传中..." style={{ marginTop: 16 }} />}
                
                {imageUrl && (
                  <div style={{ marginTop: 16, textAlign: 'center' }}>
                    <img 
                      src={imageUrl} 
                      alt="上传的图片" 
                      style={{ maxWidth: '100%', maxHeight: 300 }} 
                    />
                  </div>
                )}
              </Card>
            </Col>
            
            <Col xs={24} sm={24} md={12} lg={12}>
              <Card title="文字替换设置" bordered={false}>
                <div style={{ marginBottom: 16 }}>
                  <Text strong>原始文字：</Text>
                  <Input
                    placeholder="输入图片中需要替换的文字"
                    value={originalText}
                    onChange={(e) => setOriginalText(e.target.value)}
                    disabled={!fileId}
                  />
                </div>
                
                <div style={{ marginBottom: 16 }}>
                  <Text strong>替换文字：</Text>
                  <Input
                    placeholder="输入替换后的文字"
                    value={newText}
                    onChange={(e) => setNewText(e.target.value)}
                    disabled={!fileId}
                  />
                </div>
                
                <div style={{ marginBottom: 16 }}>
                  <Text strong>文字样式：</Text>
                  <Row gutter={[16, 16]}>
                    <Col span={8}>
                      <Tooltip title="字体">
                        <Select
                          style={{ width: '100%' }}
                          value={fontFamily}
                          onChange={setFontFamily}
                          disabled={!fileId}
                        >
                          {fontOptions.map(font => (
                            <Option key={font.value} value={font.value}>{font.label}</Option>
                          ))}
                        </Select>
                      </Tooltip>
                    </Col>
                    
                    <Col span={8}>
                      <Tooltip title="字体大小">
                        <InputNumber
                          style={{ width: '100%' }}
                          min={8}
                          max={72}
                          value={fontSize}
                          onChange={setFontSize}
                          prefix={<FontSizeOutlined />}
                          disabled={!fileId}
                        />
                      </Tooltip>
                    </Col>
                    
                    <Col span={8}>
                      <Tooltip title="字体颜色">
                        <div style={{ position: 'relative' }}>
                          <Button
                            style={{ 
                              width: '100%', 
                              backgroundColor: fontColor, 
                              borderColor: '#ddd'
                            }}
                            icon={<FontColorsOutlined style={{ color: fontColor === '#ffffff' ? '#000' : '#fff' }} />}
                            onClick={() => setShowColorPicker(!showColorPicker)}
                            disabled={!fileId}
                          />
                          
                          {showColorPicker && (
                            <div style={{ 
                              position: 'absolute', 
                              zIndex: 10, 
                              top: '40px',
                              right: 0
                            }}>
                              <SketchPicker
                                color={fontColor}
                                onChange={(color) => setFontColor(color.hex)}
                              />
                              <div style={{
                                position: 'fixed',
                                top: 0,
                                right: 0,
                                bottom: 0,
                                left: 0,
                                zIndex: -1
                              }}
                                onClick={() => setShowColorPicker(false)}
                              />
                            </div>
                          )}
                        </div>
                      </Tooltip>
                    </Col>
                  </Row>
                </div>
                
                <div style={{ marginTop: 24, textAlign: 'center' }}>
                  <Space>
                    <Button 
                      type="primary" 
                      icon={<SwapOutlined />} 
                      onClick={handleTextReplace}
                      disabled={!fileId || !originalText || !newText || processing}
                      loading={processing}
                    >
                      执行文字替换
                    </Button>
                    
                    <Button 
                      icon={<DeleteOutlined />} 
                      onClick={resetStates}
                    >
                      重新开始
                    </Button>
                  </Space>
                </div>
              </Card>
            </Col>
          </Row>
          
          {resultImageUrl && (
            <div style={{ marginTop: 24 }}>
              <Card title="处理结果" bordered={false}>
                <Row gutter={16}>
                  <Col xs={24} sm={24} md={12} lg={12} style={{ textAlign: 'center' }}>
                    <Card title="原始图片" bordered={false}>
                      <img 
                        src={imageUrl} 
                        alt="原始图片" 
                        style={{ maxWidth: '100%', maxHeight: 300 }} 
                      />
                    </Card>
                  </Col>
                  
                  <Col xs={24} sm={24} md={12} lg={12} style={{ textAlign: 'center' }}>
                    <Card title="处理后图片" bordered={false}>
                      <img 
                        src={resultImageUrl} 
                        alt="处理后图片" 
                        style={{ maxWidth: '100%', maxHeight: 300 }} 
                      />
                      
                      <div style={{ marginTop: 16 }}>
                        <Button type="primary" href={resultImageUrl} target="_blank">
                          下载处理后图片
                        </Button>
                      </div>
                    </Card>
                  </Col>
                </Row>
              </Card>
            </div>
          )}
          
          <Divider />
          
          <Card title="使用说明" bordered={false}>
            <Title level={4}>图像文字替换工具使用指南</Title>
            <Paragraph>
              <ol>
                <li>上传需要处理的图片（支持JPG、PNG等常见格式）</li>
                <li>输入原始文字（图片中要替换的文字）</li>
                <li>输入新文字（替换后的文字）</li>
                <li>调整字体样式（可选，包括字体、大小、颜色）</li>
                <li>点击"执行文字替换"按钮</li>
                <li>处理完成后，查看效果并下载处理后的图片</li>
              </ol>
            </Paragraph>
            
            <Title level={4}>注意事项</Title>
            <Paragraph>
              <ul>
                <li>目前版本为简化实现，会在图片中心位置进行替换</li>
                <li>实际替换效果可能与预期有差异，特别是对于复杂背景的图片</li>
                <li>目前仅支持简体中文和英文字符的替换</li>
                <li>大尺寸或复杂图片的处理可能需要较长时间</li>
                <li>处理结果仅保存24小时，请及时下载</li>
                <li>未来版本将支持更精确的文字定位和替换</li>
              </ul>
            </Paragraph>
          </Card>
        </div>
      </Content>
      
      <Footer style={{ textAlign: 'center' }}>
        在线工具平台 ©{new Date().getFullYear()} Created by Tool Platform Team
      </Footer>
    </Layout>
  );
};

export default TextReplaceTool; 